import {
  type ActionType, ModalForm,
  type ProColumns,
  ProTable
} from '@ant-design/pro-components';
import {Button, Descriptions, message, Tag} from 'antd';
import React, {useEffect, useRef, useState} from "react";
import {approvalStockInOrder, getStockInDetailsVo, listStockInOrderVoByPage} from "@/services/stockIn/api";

type StockInFormProps = {
  open: boolean;
  onCancel: () => void;
  stockInId: string;
}

const StockInForm: React.FC<StockInFormProps> = (props) => {
  const [data,setData] = useState<StockInOrderDetailsVo>({});
  const loadData=async ()=> {
    if(props.stockInId.length<=0){
      return;
    }
    const res = await getStockInDetailsVo({id:props.stockInId});
    if(res.code!=0){
      message.error("入库单加载失败"+res.message);
      return;
    }
    setData(res?.data||{});
  }
  const handleApproval= async ()=>{
    const res = await approvalStockInOrder({data: props.stockInId});
    if(res.code!=0 || res.data==false){
      message.error("入库单审批失败"+res.message);
      return;
    }
    message.success("入库单审批成功");
    props.onCancel();
  }

  useEffect(() => {
    loadData();
  }, [props.stockInId]);
  return (
    <ModalForm<StockInDTO>
      layout="vertical"
      open={props.open}
      onFinish={async () => {
        await handleApproval();
        // 这里处理提交逻辑
      }}
      submitter={{
        searchConfig: {
          submitText: '审批',
        },
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={
        {
          destroyOnClose: true,
          onCancel: props.onCancel,
        }
      }
    >
      <Descriptions title="入库单明细 " bordered>
        <Descriptions.Item label="入库单号">{data.stockInNo}</Descriptions.Item>
        <Descriptions.Item label="仓库名">{data.warehouseName}</Descriptions.Item>
        <Descriptions.Item label="仓库代码">{data.warehouseCode}</Descriptions.Item>
        {data?.details?.map((item, index) => (
          <>
            <Descriptions.Item label="货品代码">{item.goodsCode}</Descriptions.Item>
            <Descriptions.Item label="名称">{item.goodsName}</Descriptions.Item>
            <Descriptions.Item label="数量">{item.quantity}</Descriptions.Item>
          </>

        ))}
      </Descriptions>
    </ModalForm>
  );
};

const StockInApproval: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const [currentPage,setCurrentPage] = useState<number>(1);
  const [stockInId, setStockInId] = useState<string>('');
  const [isOpearate,setIsOperate] = useState<boolean>(false);
  const [data, setData] = useState<API.StockInOrderVo[]>([]);
  const [total,setTotal] = useState<number>(0);

  const columns: ProColumns<API.StockInOrderVo>[] = [
    {
      title: '仓库名称',
      width: 120,
      dataIndex: 'warehouseName',
    },
    {
      title: '入库单号',
      width: 120,
      dataIndex: 'stockInNo',
    },
    {
      title: '状态',
      width: 120,
      hideInSearch: true,
      render: (text, record) => {
        if (record.status===90) {
          return <Tag color="#2db7f5">完成</Tag>;
        } else {
          return <Tag color="yellow">作业中</Tag>;
        }
      },
      dataIndex: 'status',
    },
    {
      title: '创建时间',
      width: 120,
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      key: 'option',
      render: (text, record, _, action) => [
        <Button key="edit" onClick={
          ()=>{
            setIsOperate(true);
            setStockInId(record?.id||'');
          }
        } type={'primary'}>
          详情
        </Button>,
      ],
    }
  ];
  const loadData = async (params: any) => {
    const res = await listStockInOrderVoByPage({
      params : {
        ...params,
        status: 0,
      },
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code != 0) {
      message.error("入库单数据加载失败 " + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
    console.log(data);
  }
  useEffect(() => {
    loadData({});
  }, [currentPage]);
  return (
    <>
      <ProTable<API.StockInOrderVo>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={data}
        request={async (params) => {
          await loadData(params);
          return data;
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        headerTitle="入库单"
        toolBarRender={() => []}
      />
      <StockInForm open={isOpearate} onCancel={()=>setIsOperate(false)} stockInId={stockInId} />
    </>
  )
}
export default StockInApproval;


